package selectClass.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import selectClass.Ingredient;
import selectClass.Ingredient.Type;
import selectClass.Student;
import selectClass.Taco;
import selectClass.data.IngredientRepository;
import selectClass.data.StudentRepository;
import selectClass.data.TacoRepository;

import javax.validation.Valid;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@Slf4j
@Controller
@Configuration
@Validated
@RequestMapping("/design")
@SessionAttributes("taco")
public class DesignselectClassController {
    private IngredientRepository ingredientRepository;

    private TacoRepository tacoRepository;

    public DesignselectClassController(
            IngredientRepository ingredientRepository,
            TacoRepository tacoRepository
    ){
        this.ingredientRepository=ingredientRepository;
        this.tacoRepository=tacoRepository;
    }


    @GetMapping
    public String showDesignForm(Model model) {
        List<Ingredient> ingredients = new ArrayList<>();
        ingredientRepository.findAll().forEach(i -> ingredients.add(i));

        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(),
                    filterByType(ingredients, type));
        }
        return "design";
    }

    @Validated
    @PostMapping
    public String processDesign(@Valid Taco taco, Errors errors, SessionStatus sessionStatus) {
        if (errors.hasErrors()) {
            return "design";
        }

        tacoRepository.save(taco);
        sessionStatus.setComplete();

        return "information";
    }

    private List<Ingredient> filterByType(
            List<Ingredient> ingredients, Type type) {
        return ingredients
                .stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}
